package com.itheima.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private DeptServiceImpl deptService;

    @Autowired
    private EmpExprMapper empExprMapper;

    @Autowired
    private EmpMapper empMapper;

    /**
     * 条件分页查询
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<Emp> pageQuery(EmpQueryParam param) {
        //先排序，再分页
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));


        //先条件查询，再分页查询
        Page<Emp> pageResult = this.lambdaQuery()
                .like(StrUtil.isNotBlank(param.getName()), Emp::getName, param.getName())
                .eq(ObjectUtil.isNotNull(param.getGender()), Emp::getGender, param.getGender())
                .between(ObjectUtil.isNotNull(param.getBegin()) && ObjectUtil.isNotNull(param.getEnd()), Emp::getEntryDate, param.getBegin(), param.getEnd())
                .page(page);


        //对部门名称的处理
        List<Emp> records = pageResult.getRecords();
        Set<Integer> ids = records.stream().map(emp -> emp.getDeptId()).collect(Collectors.toSet());
        List<Dept> depts = deptService.listByIds(ids);
        Map<Integer, String> collect = depts.stream().collect(Collectors.toMap(dept -> dept.getId(), dept -> dept.getName()));

        for (Emp record : records) {
            record.setDeptName(collect.getOrDefault(record.getDeptId(), "闲杂部门"));
        }

        return new PageResult<Emp>(pageResult.getTotal(), records);
    }


    //==================================================

    /**
     * 新增员工和员工经历
     *
     * @param emp
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveEmp(Emp emp) {
        //设置更新时间和创建时间
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());

        //插入员工的基本数据
//        empMapper.insert(emp);
        save(emp);

        //获得员工的经历数据及获得empId的数据、插入员工工作经历数据
        List<EmpExpr> exprList = emp.getExprList();
        for (EmpExpr empExpr : exprList) {
            empExpr.setEmpId(emp.getId());
        }

        empExprMapper.insert(exprList);


    }

    //======================================

    /**
     * 根据id查询员工和经历
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Emp getEmpById(Integer id) {
        Emp emp = empMapper.selectById(id);

        LambdaQueryWrapper<EmpExpr> empExprLambdaQueryWrapper = new LambdaQueryWrapper<>();
        empExprLambdaQueryWrapper.eq(EmpExpr::getEmpId, id);
        List<EmpExpr> empExprs = empExprMapper.selectList(empExprLambdaQueryWrapper);
        emp.setExprList(empExprs);
        return emp;
    }


    //============================================

    /**
     * 修改员工基本信息和经历信息
     *
     * @param emp
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateByEmpId(Emp emp) {
        //设置修改时间
        emp.setUpdateTime(LocalDateTime.now());

        //更新基本数据
        updateById(emp);

        LambdaQueryWrapper<EmpExpr> empExprLambdaQueryWrapper = new LambdaQueryWrapper<>();
        empExprLambdaQueryWrapper.eq(EmpExpr::getEmpId, emp.getId());

        //移出原来的经历信息

        empExprMapper.delete(empExprLambdaQueryWrapper);

        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && !exprList.isEmpty()) {
            for (EmpExpr empExpr : exprList) {
                empExpr.setEmpId(emp.getId());
            }

            empExprMapper.insert(emp.getExprList());
        }



    }


    //====================================

    /**
     * 批量删除员工的基本信息和经历
     * @param ids
     */
    @Override
    public void removeByEmpId(List<Integer> ids) {
        empMapper.deleteByIds(ids);
        LambdaQueryWrapper<EmpExpr> empExprLambdaQueryWrapper = new LambdaQueryWrapper<>();
        empExprLambdaQueryWrapper.in(EmpExpr::getEmpId,ids);
        empExprMapper.delete(empExprLambdaQueryWrapper);

    }


}
